package org.zeuzgroup.tradeskill.runesofmagic;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.lang.reflect.Field;
import java.util.ArrayList;

import marvin.image.MarvinImage;
import marvin.io.MarvinImageIO;

import org.im4java.core.IMOperation;
import org.im4java.core.ImageCommand;
import org.im4java.process.ArrayListOutputConsumer;
import org.slf4j.Logger;

public class ImageDetection {

	private MarvinImage imageHerbalism, imageLumber, imageMining;

	static final Logger log = org.slf4j.LoggerFactory
			.getLogger(ImageDetection.class);

	private int sensibility = 20;

	private Robot robot = null;

	public ImageDetection(Robot robot) {
		this.robot = robot;
		imageHerbalism = MarvinImageIO.loadImage("./res/rom_herbalist.png");
		imageLumber = MarvinImageIO.loadImage("./res/rom_lumber05.png");
		imageMining = MarvinImageIO.loadImage("./res/rom_mining.png");

	}

	public Point detect() {

		Rectangle rectangle = new Rectangle(700, 50, 90, 100);

		BufferedImage mapScreenshot = robot.createScreenCapture(rectangle);

		IMOperation all = new IMOperation();

		// compare -metric RMSE -fuzz 2% grab06.png grab_b.png null
		all.fuzz(100.0);
		// RMSE AE MAE PSNR
		all.metric("PSNR");
		log.info(all.toString());
		// all.addRawArgs("-fuzz 2%");
		all.addImage();
		all.addImage();
		all.addImage(":null"); // output: convert to screen

		ArrayListOutputConsumer output = new ArrayListOutputConsumer();
		ImageCommand compare = new ImageCommand();
		compare.setCommand("compare");
		compare.setOutputConsumer(output);

		ArrayList<String> cmdOutput = null;
		try {
			compare.run(all, mapScreenshot, imageLumber.getBufferedImage());
			Field errorTexts = null;
			errorTexts = ImageCommand.class.getDeclaredField("iErrorText");

			errorTexts.setAccessible(true);

			cmdOutput = (ArrayList<String>) errorTexts.get(compare);

		} catch (Exception e) {
			log.info("something happend :", e.getCause());
		}

		Point point = null;
		for (String line : cmdOutput) {
			log.info(line);
			String[] xAndY = line.substring(line.lastIndexOf("@") + 1).split(
					",");
			int x = Integer.parseInt(xAndY[0].trim());
			int y = Integer.parseInt(xAndY[1].trim());
			point = new Point(x, y);
		}

//		if (point != null) {
//			robot.mouseMove(rectangle.x + point.x, rectangle.y + point.y);
//		}
		return point;

	}
}
